package realQuestion.baidu.review9_4;

public class JiaoTi {

    public   volatile  String  CODE="A";

    public  volatile static int NUM_COUNT=0;

    public    void  aPrint() throws InterruptedException {
        //TODO:2023/9/4 sync 控制顺序
        synchronized (this){
            //TODO:2023/9/4 让A B 交替执行
            while (!CODE.equals("A")){
                wait();
            }
            if (++NUM_COUNT<=10){
                CODE="B";
                System.out.println(Thread.currentThread().getName()+"打印A:" +NUM_COUNT);
                notify();
            }

        }
    }

    public    void  bPrint() throws InterruptedException {
        synchronized (this){
            while (!CODE.equals("B")){
                wait();
            }
            if (++NUM_COUNT<=10){
                System.out.println(Thread.currentThread().getName()+"打印B:" +NUM_COUNT);
                CODE="A";
                notify();;
            }

        }
    }

    public static void main(String[] args) {
        JiaoTi jiaoTi = new JiaoTi();
        new Thread( ()-> {
//            while (true&&NUM_COUNT<=10){
//                try {
//                    jiaoTi.aPrint();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
            for (int i = 0; i < 5; i++) {
                try {
                    jiaoTi.aPrint();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"线程A").start();


        new Thread(()->{
            //TODO:2023/9/4 下面这种形式  程序不会自动结束 线程a，b 陷入死锁的状态 互相等待对方把自己唤醒
//            while (true&&NUM_COUNT<=10){
//                try {
//                    jiaoTi.bPrint();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
            for (int i = 0; i < 5; i++) {
                try {
                    jiaoTi.bPrint();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"线程B").start();



//        Thread A = new Thread(() -> {
//            while (true) {
//                try {
//                    printA();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        });



    }




}
